package openbang.account.service.util;

import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.google.gwt.user.server.Base64Utils;

import openbang.account.service.vo.AccountServiceEnum;


public class EmailHelper {
	private static final Logger log = Logger.getLogger(EmailHelper.class.getName());
	private static Properties props = new Properties();	
	private static Session session = Session.getDefaultInstance(props, null);
	
	//系统管理员
	private static String ADMIN_EMAIL = "aibozeng@gmail.com";
	
	public static Integer send(String toMail,String subject,String body){
		return send(ADMIN_EMAIL,toMail,subject,body);
	}
	
	/**
	 * 发送邮件
	 * @param fromMail 发送人
	 * @param toMail   接收人    注:抄送固定为 aibozeng@gmail.com
	 * @param subject  标题
	 * @param body     内容(纯文本)
	 * @return retCode
	 * @see AccountServiceEnum OK , ERR_EMAIL 
	 */
	public static Integer send(String fromMail,String toMail,String subject,String body){
		Integer retCode = AccountServiceEnum.OK.getCode();
        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(fromMail));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(toMail));
            msg.addRecipient(Message.RecipientType.CC,
                    new InternetAddress(fromMail));
            //中文标题为乱码
            //BASE64Encoder encoder = new BASE64Encoder(); --- GAE 不支持
            String base64Subject="";
			try {
				base64Subject = Base64Utils.toBase64(subject.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				log.warning(e.getMessage());
			} 
            msg.setSubject("=?UTF-8?B?"+base64Subject+"?=");            
            msg.setText(body);
            Transport.send(msg);        
        } catch (AddressException e) {
        	retCode = AccountServiceEnum.EXIST_EMAIL.getCode();
        	log.warning("AddressException:"+e.getMessage());
        } catch (MessagingException e) {
        	log.warning("MessagingException:"+e.getMessage());
        	retCode = AccountServiceEnum.ERR_OTHER.getCode();
        }        
        return retCode;
	}
}
